//
//  BPScreenBlurManager.m
//  BPScreenManager_Example
//
//  Created by SiYugui on 2020/4/30.
//  Copyright © 2020年 xuhongji. All rights reserved.
//

#import "BPScreenBlurManager.h"
#import "BPScreenImage.h"

/// 屏幕宽度，会根据横竖屏的变化而变化
#define BP_SCREEN_WIDTH ([[UIScreen mainScreen] bounds].size.width)

/// 屏幕高度，会根据横竖屏的变化而变化
#define BP_SCREEN_HEIGHT ([[UIScreen mainScreen] bounds].size.height)

@interface BPScreenBlurManager()
@property (nonatomic,strong) UIImageView *blurView;
@end

@implementation BPScreenBlurManager

static BPScreenBlurManager *blur = nil;

+ (instancetype)shareInstance{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        blur = [[BPScreenBlurManager alloc] init];
    });
    return blur;
}

- (void)openScreenSafeBlur{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showBlurView) name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hidenBlurView) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)closeScreenSafeBlur{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationDidEnterBackgroundNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void)showBlurView{
    UIImage *image = [BPScreenImage currentScreenImage];
    self.blurView.image = image;
    [[UIApplication sharedApplication].keyWindow addSubview:self.blurView];
}

- (void)hidenBlurView{
    [self.blurView removeFromSuperview];
}

-(UIImageView *)blurView{
    if (!_blurView) {
        _blurView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, BP_SCREEN_WIDTH, BP_SCREEN_HEIGHT)];
        if (!UIAccessibilityIsReduceTransparencyEnabled()) {
            UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleExtraLight];
            UIVisualEffectView *blurEffectView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
            blurEffectView.frame = _blurView.bounds;
            [_blurView addSubview:blurEffectView];
            blurEffectView.alpha = 0.9;
        }
    }
    return _blurView;
}

@end
